package com.epfresh.activity;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.epfresh.R;
import com.epfresh.adapter.CenterListAdapter;
import com.epfresh.api.adapter.CommonAdapter;
import com.epfresh.api.adapter.ViewHolder;
import com.epfresh.api.constant.AppPurchaseRouterConstant;
import com.epfresh.api.entity.*;
import com.epfresh.api.entity.RequestTag;
import com.epfresh.api.entity.ResponseEntity;
import com.epfresh.api.entity.StatusEntity;
import com.epfresh.api.entity.TagPager;
import com.epfresh.api.http.HttpRequest;
import com.epfresh.api.http.OnRequestListener;
import com.epfresh.api.universalimageloader.core.ImageLoader;
import com.epfresh.api.universalimageloader.core.imageaware.ImageViewAware;
import com.epfresh.api.utils.T;
import com.epfresh.api.widget.list.LoadMoreListView;
import com.epfresh.api.widget.ptr.PtrDefaultHandler;
import com.epfresh.api.widget.ptr.PtrFrameLayout;
import com.epfresh.api.widget.ptr.PtrHandler;
import com.epfresh.api.widget.ptr.PtrMdFrameLayout;
import com.epfresh.basedialog.CustomDialog;
import com.epfresh.bean.CenterListEntity;
import com.epfresh.bean.CenterListEntity;
import com.epfresh.constant.Constant;
import com.epfresh.global.BaseActivity;
import com.epfresh.global.BaseApplication;
import com.epfresh.global.DataManager;
import com.epfresh.wxapi.WXPayEntryActivity;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class CenterListActivity extends BaseActivity implements LoadMoreListView.IXListViewListener{
    private LoadMoreListView mListView;
    private ArrayList<CenterListEntity> list;
    Context mContext;
    CenterListAdapter adapter;
    protected View mainView;
    protected View vException;
    protected TextView tvExceptionDescription;
    protected ImageView ivExceptionIcon;
    private ProgressBar pb;
    private int requestSucceedCount = 0;
    private TagPager tagPager = new TagPager();

    View tvAbout;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initView();
        list = new ArrayList<CenterListEntity>();
        mListView.setPullLoadEnable(false); // 设置可滑动
        mContext = this;
        baseback.setVisibility(View.VISIBLE);
        initHeadView();
        adapter = new CenterListAdapter(mContext, list);
        mListView.setAdapter(adapter);
        requestOrderList(0);
    }

    void initView(){
        setContentView(R.layout.activity_center_list);
        mListView = (LoadMoreListView)findViewById(R.id.listview);
        basetitle.setText("配送中心列表");
        vException = findViewById(R.id.v_exception);
        mainView = findViewById(R.id.fragment_ptr_home_ptr_frame);
        initException();
        tvAbout = findViewById(R.id.tv_about);
        tvAbout.setOnClickListener(this);
    }


    public void initException() {
        tvExceptionDescription = (TextView) vException.findViewById(R.id.tv_exception);
        ivExceptionIcon = (ImageView) vException.findViewById(R.id.iv_exception);
        pb = (ProgressBar) vException.findViewById(R.id.pb);
    }


    public void showMainView() {
        vException.setVisibility(View.GONE);
        mainView.setVisibility(View.VISIBLE);
    }


    public void showExceptionView(int imgSrc, String text, int exceptionType) {
        if (imgSrc > 0) {

        }
        pb.setVisibility(View.GONE);
        vException.setVisibility(View.VISIBLE);
        tvExceptionDescription.setVisibility(View.VISIBLE);
        ivExceptionIcon.setVisibility(View.VISIBLE);
        mainView.setVisibility(View.GONE);

        ivExceptionIcon.setImageResource(imgSrc);
        tvExceptionDescription.setText(text);
        tvExceptionDescription.setTag(exceptionType);
        ivExceptionIcon.setTag(exceptionType);
        tvExceptionDescription.setOnClickListener(this);
        ivExceptionIcon.setOnClickListener(this);
    }
    public void showProgressView() {

        pb.setVisibility(View.VISIBLE);
        vException.setVisibility(View.VISIBLE);
        tvExceptionDescription.setVisibility(View.GONE);
        ivExceptionIcon.setVisibility(View.GONE);
        mainView.setVisibility(View.GONE);
    }


    private PtrMdFrameLayout ptrFrameLayout;
    private PtrHandler ptrHandler = new PtrHandler() {
        @Override
        public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
            return false;
        }

        @Override
        public void onRefreshBegin(PtrFrameLayout frame) {
            refresh();
        }
    };

    private void initHeadView() {
        ptrFrameLayout = (PtrMdFrameLayout) findViewById(R.id.fragment_ptr_home_ptr_frame);
        ptrFrameLayout.setPtrHandler(ptrHandler);
        hideProgressDialog();
        showMainView();
    }

    boolean refreshFlag = false;
    public void refresh() {
        mListView.resetNoMore();
        refreshFlag = true;
        //requestOrderList(0);
    }

    @Override
    public void onLoadMore() {
        int number = tagPager.getNumber();
       // requestOrderList( number + 1);
    }


    public void updateViewStatus(RequestTag requestTag) {
        ptrFrameLayout.refreshComplete();
        if (tagPager.isLast()) {
            mListView.noMore();
        } else {
            mListView.stopLoadMore();
        }
    }
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.baseback:
                // 返回上一页
                finish();
                break;
            case R.id.tv_about:
                Intent pro = new Intent(this, WebActivity.class);
                pro.putExtra(Constant.KEY_WEB_URL, Constant.URL_HELP_BEBUY);
                pro.putExtra(Constant.KEY_WEB_TITLE, "");
                //pro.putExtra("title","结算历程及规则");
                startActivity(pro);
                break;
        }
    }


    OnRequestListener<List<CenterListEntity>> onRequestListener = new OnRequestListener<List<CenterListEntity>>() {
        @Override
        public List<CenterListEntity> jsonToObj(String responseStr) {
            return new Gson().fromJson(responseStr, new TypeToken<List<CenterListEntity>>() {
            }.getType());
        }

        @Override
        public void onFail(int failCode, Object arg, Object tag) {
            RequestTag requestTag = (RequestTag) tag;
            updateViewStatus(requestTag);
            if (requestSucceedCount == 0){
                showExceptionView(R.mipmap.order_no, "网络问题,请点击重试", HttpRequest.FAIL_NET_FAULT);
            }
            finish();
        }

        @Override
        public void onResponseError(int failCode, Object arg, Object tag) {
            if (requestSucceedCount == 0){
                showExceptionView(R.mipmap.order_no, arg + "", HttpRequest.FAIL_DATA_FAULT);//arg + ",请点击重试"
            }
            RequestTag requestTag = (RequestTag) tag;
            updateViewStatus(requestTag);
            finish();
        }

        @Override
        public void onStart(Object tag) {
            if (requestSucceedCount == 0){
                showProgressView();
            }
        }

        @Override
        public void onResponse(ResponseEntity<List<CenterListEntity>> response, Object tag) {
            showMainView();
            list.clear();
            List<CenterListEntity> orderResponse = response.getResponseElement();
            for(int i=0;i<orderResponse.size();i++){
                for(int j=0;orderResponse.get(i).getStores()!=null&&j<orderResponse.get(i).getStores().size();j++){
                    CenterListEntity flag = new CenterListEntity();
                    flag.setId(orderResponse.get(i).getId());
                    flag.setName(orderResponse.get(i).getName());
                    flag.setStore(orderResponse.get(i).getStores().get(j));
                    list.add(flag);
                }
            }

            adapter.notifyDataSetChanged();
            updateViewStatus(requestTag);
            if(list.size()==0){
                showExceptionView(R.mipmap.coupon_no, "当前没有可绑定的配送中心", HttpRequest.FAIL_DATA_EMPTY);
            }

        }
    };



    private RequestTag requestTag = new RequestTag();

    public void requestOrderList(int page) {

        RequestEntityPurchase<Map<String, String>> entity = new RequestEntityPurchase<>();
        Map<String, String> map = new HashMap<>();
        entity.setCmd(AppPurchaseRouterConstant.cmd_store_store_dcStores);
        entity.setParameters(map);
        requestTag.tag = "store/dcStores";
        requestTag.action = page;
        request(entity, requestTag, onRequestListener);
    }
    /** 绑定 */
    public void mHttpSure(final String id) {
        RequestEntityPurchase<Map<String, String>> data = new RequestEntityPurchase<>();
        //data.setCmd("store/bind");
        data.setCmd(AppPurchaseRouterConstant.cmd_store_store_bind);
        Map<String, String> map = new HashMap<>();
        map.put("storeId", id);
        data.setParameters(map);
        request(data, "store/bind", new OnRequestListener<StatusEntity>() {
            @Override
            public StatusEntity jsonToObj(String responseStr) {
                return new Gson().fromJson(responseStr, StatusEntity.class);
            }

            @Override
            public void onFail(int failCode, Object arg, Object tag) {
                hideProgressDialog();
                Toast.makeText(mContext, "服务器开小差了……", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onResponseError(int failCode, Object arg, Object tag) {
                hideProgressDialog();
                toast((arg == null ? "" : arg + ""));
            }

            @Override
            public void onStart(Object tag) {
                showProgressDialog();
            }
            @Override
            public void onResponse(ResponseEntity<StatusEntity> response, Object tag) {
                hideProgressDialog();
                StatusEntity responseElement = response.getResponseElement();
                if (responseElement.isSuccess()) {
                    requestOrderList(0);
                    DataManager.getInstance().bindStoreReFresh = true;
                    T.toast("绑定中");
                }else {
                    T.toast("服务器出现小问题，请稍后再试");
                }
            }
        });
    }

}
